package com.ustb.util;

import java.util.Locale;

public class HexUtil {

    public static String string2HexString(String strPart) {
        byte[] bytes=strPart.getBytes();
        StringBuffer hexString=new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            //1byte占8位
            byte ch1=(byte)((bytes[i]>>4)&0x0F);   //高位数字
            byte ch2=(byte)(bytes[i]&0x0F);      //低位数字
            String strHex = Integer.toHexString(ch1)+Integer.toHexString(ch2);
            hexString.append(strHex);
        }
        return hexString.toString();
    }

    /**
     * @Title:hexString2String
     * @Description:16进制字符串转字符串
     * @param hexStr
     *            16进制字符串
     * @return 字节数组
     * @throws
     */
    public static String hexString2String(String hexStr) {
        String mHexStr = "0123456789ABCDEF";
        hexStr = hexStr.toString().trim().replace(" ", "").toUpperCase(Locale.US);
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int iTmp = 0x00;;

        for (int i = 0; i < bytes.length; i++){
            iTmp = mHexStr.indexOf(hexs[2 * i]) << 4;
            iTmp |= mHexStr.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (iTmp & 0xFF);
        }
        return new String(bytes);
    }


}
